package com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.analysis.vo.HddcAppZztCountVo;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.HddcGeologicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyFaultSvyPoint.repository.entity.HddcWyFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.repository.HddcWyGeologicalsvypointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.repository.HddcWyGeologicalsvypointRepository;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.repository.entity.HddcWyGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.service.HddcWyGeologicalsvypointService;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.viewobjects.HddcWyGeologicalsvypointQueryParams;
import com.css.zfzx.sjcj.modules.hddcwyGeologicalSvyPoint.viewobjects.HddcWyGeologicalsvypointVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zyb
 * @date 2020-12-01
 */
@Service
public class HddcWyGeologicalsvypointServiceImpl implements HddcWyGeologicalsvypointService {

	@Autowired
    private HddcWyGeologicalsvypointRepository hddcWyGeologicalsvypointRepository;
    @Autowired
    private HddcWyGeologicalsvypointNativeRepository hddcWyGeologicalsvypointNativeRepository;
    @Autowired
    private HddcGeologicalsvypointRepository hddcGeologicalsvypointRepository;

    @Override
    public JSONObject queryHddcWyGeologicalsvypoints(HddcWyGeologicalsvypointQueryParams queryParams,int curPage,int pageSize) {
        Page<HddcWyGeologicalsvypointEntity> hddcWyGeologicalsvypointPage = this.hddcWyGeologicalsvypointNativeRepository.queryHddcWyGeologicalsvypoints(queryParams,curPage,pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWyGeologicalsvypointPage);
        return jsonObject;
    }


    @Override
    public HddcWyGeologicalsvypointEntity getHddcWyGeologicalsvypoint(String uuid) {
        HddcWyGeologicalsvypointEntity hddcWyGeologicalsvypoint = this.hddcWyGeologicalsvypointRepository.findById(uuid).orElse(null);
         return hddcWyGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvypointEntity saveHddcWyGeologicalsvypoint(HddcWyGeologicalsvypointEntity hddcWyGeologicalsvypoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcWyGeologicalsvypoint.setUuid(uuid);
        if(StringUtils.isEmpty(hddcWyGeologicalsvypoint.getCreateUser())){
            hddcWyGeologicalsvypoint.setCreateUser(PlatformSessionUtils.getUserId());
        }
        hddcWyGeologicalsvypoint.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWyGeologicalsvypoint.setIsValid("1");

        HddcGeologicalsvypointEntity hddcGeologicalsvypointEntity=new HddcGeologicalsvypointEntity();
        BeanUtils.copyProperties(hddcWyGeologicalsvypoint,hddcGeologicalsvypointEntity);
        hddcGeologicalsvypointEntity.setExtends4(hddcWyGeologicalsvypoint.getTown());
        hddcGeologicalsvypointEntity.setExtends5(String.valueOf(hddcWyGeologicalsvypoint.getLon()));
        hddcGeologicalsvypointEntity.setExtends6(String.valueOf(hddcWyGeologicalsvypoint.getLat()));
        this.hddcGeologicalsvypointRepository.save(hddcGeologicalsvypointEntity);

        this.hddcWyGeologicalsvypointRepository.save(hddcWyGeologicalsvypoint);
        return hddcWyGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWyGeologicalsvypointEntity updateHddcWyGeologicalsvypoint(HddcWyGeologicalsvypointEntity hddcWyGeologicalsvypoint) {
        HddcWyGeologicalsvypointEntity entity = hddcWyGeologicalsvypointRepository.findById(hddcWyGeologicalsvypoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcWyGeologicalsvypoint);
        hddcWyGeologicalsvypoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWyGeologicalsvypoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWyGeologicalsvypointRepository.save(hddcWyGeologicalsvypoint);
        return hddcWyGeologicalsvypoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWyGeologicalsvypoints(List<String> ids) {
        List<HddcWyGeologicalsvypointEntity> hddcWyGeologicalsvypointList = this.hddcWyGeologicalsvypointRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWyGeologicalsvypointList) && hddcWyGeologicalsvypointList.size() > 0) {
            for(HddcWyGeologicalsvypointEntity hddcWyGeologicalsvypoint : hddcWyGeologicalsvypointList) {
                this.hddcWyGeologicalsvypointRepository.delete(hddcWyGeologicalsvypoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public BigInteger queryHddcWyGeologicalsvypoint(HddcAppZztCountVo queryParams) {
        BigInteger bigInteger = hddcWyGeologicalsvypointNativeRepository.queryHddcWyGeologicalsvypoint(queryParams);
        return bigInteger;
    }

    @Override
    public List<HddcWyGeologicalsvypointEntity> findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(String userId, String taskId, String projectId, String isValid) {
        List<HddcWyGeologicalsvypointEntity> list = hddcWyGeologicalsvypointRepository.findAllByCreateUserAndTaskIdAndProjectIdAndIsValid(userId, taskId, projectId, isValid);
        return list;
    }

    @Override
    public void exportFile(HddcAppZztCountVo queryParams, HttpServletResponse response) {
        List<HddcWyGeologicalsvypointEntity> hddcWyGeologicalsvypointEntity = hddcWyGeologicalsvypointNativeRepository.exportPoint(queryParams);
        List<HddcWyGeologicalsvypointVO> list=new ArrayList<>();
        for (HddcWyGeologicalsvypointEntity entity:hddcWyGeologicalsvypointEntity) {
            HddcWyGeologicalsvypointVO hddcWyGeologicalsvypointVO=new HddcWyGeologicalsvypointVO();
            BeanUtils.copyProperties(entity,hddcWyGeologicalsvypointVO);
            list.add(hddcWyGeologicalsvypointVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"地质调查观测点-点","地质调查观测点-点", HddcWyGeologicalsvypointVO.class,"地质调查观测点-点.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWyGeologicalsvypointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWyGeologicalsvypointVO.class, params);
            List<HddcWyGeologicalsvypointVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWyGeologicalsvypointVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWyGeologicalsvypointVO hddcWyGeologicalsvypointVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + hddcWyGeologicalsvypointVO.getRowNum() + "行" + hddcWyGeologicalsvypointVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcWyGeologicalsvypointVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWyGeologicalsvypointEntity hddcWyGeologicalsvypointEntity = new HddcWyGeologicalsvypointEntity();
            HddcWyGeologicalsvypointVO hddcWyGeologicalsvypointVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(hddcWyGeologicalsvypointVO, hddcWyGeologicalsvypointEntity);
            saveHddcWyGeologicalsvypoint(hddcWyGeologicalsvypointEntity);
        }
    }
    @Override
    public List<HddcWyGeologicalsvypointEntity> findAllByCreateUserAndIsValid(String userId,String isValid) {
        List<HddcWyGeologicalsvypointEntity> list = hddcWyGeologicalsvypointRepository.findAllByCreateUserAndIsValid(userId,isValid);
        return list;
    }


    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcWyGeologicalsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeologicalsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskId
     */
    @Override
    public void deleteByTaskId(List<String> taskId) {
        List<HddcWyGeologicalsvypointEntity> hddcA1InvrgnhasmaterialtableList = this.hddcWyGeologicalsvypointRepository.queryHddcA1InvrgnhasmaterialtablesByTaskId(taskId);
        if(!PlatformObjectUtils.isEmpty(hddcA1InvrgnhasmaterialtableList) && hddcA1InvrgnhasmaterialtableList.size() > 0) {
            for(HddcWyGeologicalsvypointEntity hddcA1Invrgnhasmaterialtable : hddcA1InvrgnhasmaterialtableList) {
                hddcA1Invrgnhasmaterialtable.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcA1Invrgnhasmaterialtable.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcA1Invrgnhasmaterialtable.setIsValid("0");
                this.hddcWyGeologicalsvypointRepository.save(hddcA1Invrgnhasmaterialtable);
            }
        }

    }









}
